<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form ref="registerForm" size="large" autocomplete="off" v-if="isRegister" :model="registerData"
               :rules="registerRules">
        <!-- 注册表单 -->
        <el-form ref="registerForm" size="large" autocomplete="off" v-if="isRegister" :model="registerData"
                 :rules="registerRules">
          <el-form-item>
            <h1>注册</h1>
          </el-form-item>
          <el-form-item prop="userName">
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.userName"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                      v-model="registerData.password"></el-input>
          </el-form-item>
          <el-form-item prop="rePassword">
            <el-input :prefix-icon="Lock" type="password" placeholder="请再次输入密码"
                      v-model="registerData.rePassword"></el-input>
          </el-form-item>
          <el-form-item prop="name">
            <el-input placeholder="请输入真实姓名" v-model="registerData.name"></el-input>
          </el-form-item>
          <el-form-item prop="sex">
            <el-radio-group v-model="registerData.sex">
              <el-radio :label="'male'">
                <el-icon>
                  <Male/>
                </el-icon>
                男
              </el-radio>
              <el-radio :label="'female'">
                <el-icon>
                  <Female/>
                </el-icon>
                女
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="tel">
            <el-input :prefix-icon="Phone" placeholder="请输入电话号码" v-model="registerData.tel"></el-input>
          </el-form-item>
          <el-form-item prop="sfID">
            <el-input :prefix-icon="IdCard" placeholder="请输入身份证号" v-model="registerData.sfID"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="button" type="primary" auto-insert-space @click="register">注册</el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false" @click="isRegister = false; clearRegisterData()">← 返回</el-link>
          </el-form-item>
        </el-form>
      </el-form>

      <!-- 登录表单 -->
      <el-form ref="loginForm" size="large" autocomplete="off" v-else :model="loginData" :rules="loginRules">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="userName">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="loginData.userName"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                    v-model="loginData.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="isAdmin">管理员</el-checkbox>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true; clearLoginData()">注册 →</el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {loginUser, getUserByUsername, registerUser} from "@/api/user";
import { useTokenStore } from "@/store/token";
import { useRouter } from 'vue-router';
import axios from "axios";

// 控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)
// 定义数据模型
const registerData = ref({
  userName: '',
  password: '',
  rePassword: '',
  name: '',
  sex: '',
  tel: '',
  sfID: ''
})

// 校验密码的函数
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value !== registerData.value.password) {
    callback(new Error('请确保两次输入的密码一样'))
  } else {
    callback()
  }
}

// 定义表单校验规则
const registerRules = {
  userName: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur'}
  ],
  rePassword: [
    {validator: checkRePassword, trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入真实姓名', trigger: 'blur'}
  ],
  sex: [
    {required: true, message: '请选择性别', trigger: 'change'}
  ],
  tel: [
    {required: true, message: '请输入电话号码', trigger: 'blur'},
    {pattern: /^[0-9]{11}$/, message: '请输入有效的11位电话号码', trigger: 'blur'}
  ],
  sfID: [
    {required: true, message: '请输入身份证号', trigger: 'blur'},
    {pattern: /^[0-9]{18}$/, message: '请输入有效的18位身份证号', trigger: 'blur'}
  ]
}


const router = useRouter();
const isAdmin = ref(false);
const loginData = ref({
  userName: '',
  password: ''
});

const loginRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ]
};

const tokenStore = useTokenStore();

const clearLoginData = () => {
  loginData.value = {
    userName: '',
    password: ''
  };
};

// 定义函数,清空注册表单数据模型的数据
const clearRegisterData = () => {
  registerData.value = {
    userName: '',
    password: '',
    rePassword: '',
    name: '',
    sex: '',
    tel: '',
    sfID: ''
  }
}

// 注册函数
const register = async () => {
  try {
    const response = await registerUser(registerData.value);
    if (response.code === 1) {
      ElMessage.success('注册成功');
      clearRegisterData();
      isRegister.value = false;
    } else {
      ElMessage.error(response.msg || '注册失败，请重试');
    }
  } catch (error) {
    ElMessage.error('注册失败，请重试');
    console.error('Error during registration:', error);
  }
}

const login = async () => {
  if (isAdmin.value) {
    // 管理员登录验证
    if (loginData.value.userName === 'admin' && loginData.value.password === '123456789') {
      const token = localStorage.getItem("token");
      axios.defaults.headers.common['token'] = token;

      router.push('/admin');
      ElMessage.success('管理员登录成功');
    } else {
      ElMessage.error('管理员用户名或密码错误');
    }
  } else {
    // 普通用户登录验证
    try {
      const response = await loginUser(loginData.value);
      if (response.code === 1) {
        ElMessage.success('登录成功');
        localStorage.setItem('token', response.data);
        console.log("登录令牌：",response.data)
        localStorage.setItem("uname", loginData.value.userName);
        localStorage.setItem('loggedIn', 'true');
        // 设置请求头，将令牌发送给后端
        axios.defaults.headers.common['token'] = response.data;
        router.push('/'); // 默认跳转到用户个人资料页面

        // 获取用户详细信息并存储在localStorage中
        const userResponse = await getUserByUsername(loginData.value.userName);
        if (userResponse.code === 1) {
          localStorage.setItem('userInfo', JSON.stringify(userResponse.data));
          console.log("登录界面获取用户信息："+localStorage.getItem("userInfo"))
        } else {
          ElMessage.error('获取用户信息失败');
        }
      } else {
        ElMessage.error(response.msg || '登录失败，请重试');
      }
    } catch (error) {
      ElMessage.error('登录失败，请重试');
      console.error('Error during login:', error);
    }
  }
};

</script>

<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background:
        //url('@/assets/images/logo2.png') no-repeat 60% center / 240px auto,
    url('@/assets/images/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
